// 通用的事件绑定函数
function bindEvent(elem, type, fn) {
  elem.addEventListener(type, fn);
}

// 可以支持普通绑定和代理绑定两种方式
function bindEvent(elem, type, selector, fn) {
  if (fn == null) {
    fn = selector;
    selector = null;
  }

  elem.addEventListener(type, (event) => {
    if (selector == null) {
      // 普通绑定
      fn(event);
    } else {
      // 代理绑定
      if (event.target.matches(selector)) {
        // 命中，调用回调函数
        fn.call(event.target, event);
      }
    }
  });
}

const a = document.getElementById("link1");

bindEvent(a, "click", (e) => {
  e.preventDefault(); // 阻止默认行为
  alert("clicked");
});

bindEvent(a, "click", (e) => {
  e.stopPropagation(); // 阻止冒泡行为
  alert("激活");
});

const div3 = document.getElementById("div3");

bindEvent(div3, "click", (e) => {
  e.preventDefault();

  const target = e.target;

  // 点击的目标是a标签
  if (target.nodeName === "A") {
    alert(target.innerHtml);
  }
});
